package com.klikmee.sms.core.base.dao;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.model.DistributionListItem;

public class DistributionListItemDAO extends AbstractDAO<DistributionListItem> {
	
	private Logger logger  = Logger.getLogger( DistributionListItemDAO.class );
	public DistributionListItemDAO() {
		super( DistributionListItem.class );
	}

	public DistributionListItem findByMtsServiceIdListIdAndMsisdn( String serviceId, String distributionListId, String msisdn ) {
		
		try {
			return (DistributionListItem) entityManager.createNamedQuery( "DistributionListItem.findByMtsServiceIdListIdAndMsisdn" )
			.setParameter( "serviceId", serviceId)
			.setParameter( "listId", distributionListId)
			.setParameter( "msisdn", msisdn)
			.getSingleResult();
		} catch (NoResultException e) {
			logger.warn( String.format( "Could not find distribution list item for mtsServiceId = [%s], mtsListId = [%s] and msisdn = [%s]", serviceId, distributionListId, msisdn ), e );
			return null;
		}
	}
	
	@Override
	public void remove( DistributionListItem entity ) {
		
		DistributionListItem mergedItem = entityManager.merge( entity );
		mergedItem.getDistributionList().getDistributionListItemSet().remove( entity );
		entityManager.remove( mergedItem );
		
	}
	
	public int deleteByMsisdn(String msisdn){
		return entityManager.createNamedQuery( "DistributionListItem.deleteByMsisdn" ).setParameter( "msisdn", msisdn ).executeUpdate();
	}
	
}
